package com.zzq.guli.service.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.zzq.guli.service.oss.service.FileService;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import org.springframework.stereotype.Service;


import java.io.InputStream;


@Service
public class FileServiceImpl implements FileService {


    //文件上传服务
    @Override
    public String fileUpload(InputStream fileInputStream,String fileName) {

        String endpoint = "oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI5tH9bEpTKFdooE3jQhVm";
        String accessKeySecret = "M5JYfdI4abNb33uwneGFVkd9bYPxAM";
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String bucketName = "zzq-guli";


        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, fileInputStream);
            // 创建PutObject请求。
            PutObjectResult result = client.putObject(putObjectRequest);
        } catch (OSSException e) {
            throw new RuntimeException(e);
        } finally {
            if (client != null) {
                client.shutdown();
            }

            return "https://"+bucketName+"."+endpoint + "/" + fileName;
        }
    }

    @Override
    public Boolean removeImage(String filePath) {
        String endpoint="oss-cn-beijing.aliyuncs.com";
        String accessKeyId="LTAI5tH9bEpTKFdooE3jQhVm";
        String accessKeySecret="M5JYfdI4abNb33uwneGFVkd9bYPxAM";
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String bucketName = "zzq-guli";
        String replace = filePath.replace("http://zzq-guli.oss-cn-beijing.aliyuncs.com/", "");
        try {
            client.deleteObject(bucketName,replace);
            return true;
        } catch (OSSException e) {
            throw new RuntimeException(e);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }

    }
}
